<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>推流页面</title>
  </head>

  <body>
    <video id="remoteStream" style="width: 320px; height: 240px;" autoplay muted></video>
    <button id="deviceBtn">打开本地摄像头</button>
    <button id="startBtn">建立连接</button>
    <script>
      // 显示本地画面的VideoElement
      let remoteStream = document.getElementById("remoteStream");

      // 订阅流用的Peerconnection
      let pc_sub = new RTCPeerConnection();

      let ws = new WebSocket('ws://127.0.0.1:9000');
      ws.addEventListener('open', () => {
        // 通知server pub已经上线
        ws.send(JSON.stringify({
          type: "subscribe"
        }))
      })

      ws.addEventListener('message', (event) => {
        let msg = JSON.parse(event.data);
        switch (msg.type) {
          case "start":
            break;

          case "offer":
            pc_sub.setRemoteDescription(msg).then(() => {
              pc_sub.createAnswer().then((answer) => {
                pc_sub.setLocalDescription(answer).then(() => {
                  ws.send(JSON.stringify(answer));
                }).catch((err) => {

                })
              }).catch((err) => {
                console.error('create answer error', err);
              })
            }).catch((err) => {
              console.error('setRemoteDescription error', err);
            })
            break;

          default:
            pc_sub.addIceCandidate(msg);
            break;
        }
      })

      pc_sub.addEventListener('icecandidate', (event) => {
        if (event.candidate) {
          ws.send(JSON.stringify(event.candidate));
        }
      })

      pc_sub.addEventListener('track', (event) => {
        remoteStream.srcObject = event.streams[0];
      })

    </script>
  </body>

</html>